import TagGroup from '@/components/TagGroup';
import UploadDragger from '@/pages/cues/components/UploadDragger';
import { listCuesIndustry } from '@/services/api/api-cues-industry';
import { saveCuesSubmit } from '@/services/api/api-cues-submit';
import {
  CheckCircleTwoTone,
  FileSearchOutlined,
  PlusOutlined,
  SendOutlined,
} from '@ant-design/icons';
import {
  DrawerForm,
  ModalForm,
  ProCard,
  ProForm,
  ProFormDatePicker,
  ProFormInstance,
  ProFormList,
  ProFormSelect,
  ProFormText,
  ProFormTextArea,
  ProList,
} from '@ant-design/pro-components';

import { ActionType } from '@ant-design/pro-table';
import { Button, Col, message, Row } from 'antd';
import FormItem from 'antd/es/form/FormItem';
import dayjs from 'dayjs';
import 'dayjs/locale/zh-cn';
import React, { useRef, useState } from 'react';
import { useAccess } from 'umi';
import AddSubmitPreview from './AddSubmitPreview';
import { isEmpty } from 'lodash';

interface AddSubmitProps {
  topicId: string;
  topicName: string;
  onRefurbish: () => void;
  eventNum?: string;
}

const AddSubmit: React.FC<AddSubmitProps> = ({ topicId, topicName, onRefurbish, eventNum }) => {
  const access = useAccess();

  const actionRef = useRef<ActionType>();

  const formRef = useRef<ProFormInstance>();

  const [industrys, setIndustrysState] = useState<any[]>([]);

  const [openAddSubmit, setOpenAddSubmit] = useState<boolean>(false);

  const [openAddSubmitPreview, setOpenAddSubmitPreview] = useState<boolean>(false);
  const [previewData, setPreviewData] = useState<CuesSubmitBo.AddSubmitPreview>();

  const [modalFormOpen, setModalFormOpenState] = useState<boolean>(false);

  const [green, setGreen] = useState<boolean>(false);

  /**
   * 加载权限详情
   * @param key
   */
  const getCuesIndustryData = async () => {
    try {
      const response = await listCuesIndustry();

      setIndustrysState(
        response.data.map((item) => {
          return { label: item.name, value: item.id };
        }),
      );
    } catch (error) {}
  };

  return (
    <DrawerForm
      key="drawer_form_add_submit"
      title="报送线索"
      drawerProps={{
        maskClosable: false,
        destroyOnClose: true,
        width: 680,
      }}
      formRef={formRef}
      trigger={
        <Button key="button_add_submit" type="primary">
          <PlusOutlined />
          报送线索
        </Button>
      }
      initialValues={{}}
      open={openAddSubmit}
      onOpenChange={(visible) => {
        setOpenAddSubmit(visible);
        if (visible) {
          getCuesIndustryData();
        }
      }}
      layout="horizontal"
      submitter={{
        searchConfig: {
          submitText: (
            <>
              <FileSearchOutlined /> 预览
            </>
          ),
        },
        render: (props, defaultDoms) => {
          return [
            defaultDoms,
            <Button
              key="button_add_submit"
              icon={<SendOutlined />}
              type="primary"
              style={{
                background: '#87d068',
              }}
              onClick={() => {
                /**
                 * ======================
                 * 直接发布
                 * ======================
                 */
                const values = formRef.current?.getFieldsValue();

                if (!(values.articleName !== undefined && values.articleName.length > 0)) {
                  message.warning('请输入标题');
                  return;
                }

                if (
                  !(values.articleIndustryIds !== undefined && values.articleIndustryIds.length > 0)
                ) {
                  message.warning('请选择至少一个选题方向');
                  return;
                }

                if (!(values.articleLabels !== undefined && values.articleLabels.length > 0)) {
                  message.warning('请输入至少一个标签');
                  return;
                }

                if (!(values.articleContent !== undefined && values.articleContent.length > 0)) {
                  message.warning('请输入线索内容');
                  return;
                }
                if (!(values.contacts && values.contacts.length > 0)) {

                } else {
                  let required = false;
                  let unable = false;
                  const phoneRegex =
                    /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/;
                  values.contacts.forEach((element: { name: any; phone: any }) => {
                    console.log('====', element, phoneRegex.test(element.phone));
                    if (element.phone == undefined || element.phone.length == 0  || isEmpty(element.name)) {
                      required = true;
                    }
                    if (!phoneRegex.test(element.phone)) {
                      unable = true;
                    }
                  });

                  if (required) {
                    message.warning('请补充联络人信息');
                    return;
                  }
                  if (unable) {
                    message.warning('请输入正确的联系电话');
                    return;
                  }
                }
                setModalFormOpenState(true);
              }}
            >
              提交
            </Button>,
            <AddSubmitPreview
              key="add_submit_preview"
              onSubmit={() => {
                setOpenAddSubmit(false);
                onRefurbish();
              }}
              open={openAddSubmitPreview}
              onOpenChange={(open) => {
                setOpenAddSubmitPreview(open);
              }}
              details={previewData}
            />,
            <ModalForm
              key={'modal_form_add_submit'}
              title={
                <>
                  <CheckCircleTwoTone
                    style={{
                      marginRight: 8,
                    }}
                    twoToneColor="#87d068"
                  />
                  确认提交
                </>
              }
              autoFocusFirstInput
              modalProps={{
                width: 400,
                destroyOnClose: true,
              }}
              open={modalFormOpen}
              onOpenChange={setModalFormOpenState}
              submitTimeout={2000}
              submitter={{
                submitButtonProps: {
                  type: 'primary',
                  style: { background: '#87d068' },
                },
              }}
              onFinish={async () => {
                const values = formRef.current?.getFieldsValue();

                if (
                  values.articleAttachments !== undefined &&
                  values.articleAttachments.length > 0
                ) {
                  const articleAttachments = values.articleAttachments.map(
                    (item: { response: { data: { id: any } } }) => {
                      return item.response.data.id;
                    },
                  );

                  values.articleAttachments = articleAttachments;
                }

                if (values.articleSetDate) {
                  values.articleSetDate = dayjs(values.articleSetDate).format('YYYY-MM-DD');
                }

                const response = await saveCuesSubmit({
                  topicId,
                  eventNum,
                  articleName: values?.articleName,
                  articleIndustryIds: values?.articleIndustryIds,
                  articleLabels: values?.articleLabels,
                  articleSetDate: values?.articleSetDate,
                  articleLocation: values?.articleLocation,
                  articleHighlight: values?.articleHighlight,
                  contacts: values?.contacts,
                  articleContent: values?.articleContent,
                  articleAttachments: values?.articleAttachments,
                  createdSource: 1,
                });

                if (response.code === 0) {
                  message.success('提交成功');
                  setOpenAddSubmit(false);
                  onRefurbish();
                  return true;
                } else {
                  return false;
                }
              }}
            />,
          ];
        },
      }}
      onFinish={async (values) => {
        /**
         * ======================
         * 预览发布
         * ======================
         */
        if (!(values.articleName !== undefined && values.articleName.length > 0)) {
          message.warning('请输入标题');
          return;
        }

        if (!(values.articleIndustryIds !== undefined && values.articleIndustryIds.length > 0)) {
          message.warning('请选择至少一个选题方向');
          return;
        }

        if (!(values.articleLabels !== undefined && values.articleLabels.length > 0)) {
          message.warning('请输入至少一个标签');
          return;
        }

        if (!(values.articleContent !== undefined && values.articleContent.length > 0)) {
          message.warning('请输入线索内容');
          return;
        }
        if (!(values.contacts && values.contacts.length > 0)) {

        } else {
          let required = false;
          let unable = false;
          const phoneRegex =
            /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/;
          values.contacts.forEach((element: { name: any; phone: any }) => {
            console.log('====', element, phoneRegex.test(element.phone));
            if (element.phone == undefined || element.phone.length == 0  || isEmpty(element.name) ) {
              required = true;
            }
            if (!phoneRegex.test(element.phone)) {
              unable = true;
            }
          });

          if (required) {
            message.warning('请补充联络人信息');
            return;
          }
          if (unable) {
            message.warning('请输入正确的联系电话');
            return;
          }
        }
        const articleIndustrys = values.articleIndustryIds?.map((item) => {
          const industry = industrys.find((e) => e.value === item);
          return industry;
        });

        if (values.articleSetDate) {
          values.articleSetDate = dayjs(values.articleSetDate).format('YYYY-MM-DD');
        }

        setPreviewData({
          topicId: topicId,
          topicName: topicName,
          articleName: values.articleName,
          articleIndustrys: articleIndustrys,
          articleLabels: values.articleLabels,
          articleSetDate: values.articleSetDate,
          articleLocation: values.articleLocation,
          articleHighlight: values.articleHighlight,
          contacts: values.contacts,
          articleContent: values.articleContent,
          createdSource: 1,
          articleAttachments: values.articleAttachments,
        });

        setOpenAddSubmitPreview(true);
      }}
    >
      <ProFormText
        width="xl"
        name="articleName"
        label={
          <>
            <span
              style={{
                color: '#ff4d4f',
                fontSize: 14,
                paddingRight: 4,
              }}
            >
              *
            </span>
            标题
          </>
        }
        fieldProps={{
          allowClear: true,
          maxLength: 50,
          showCount: true,
          style: {
            marginLeft: '28px',
          },
        }}
      />

      <ProFormSelect
        width="xl"
        name="articleIndustryIds"
        label={
          <>
            <span
              style={{
                color: '#ff4d4f',
                fontSize: 14,
                paddingRight: 4,
              }}
            >
              *
            </span>
            选题方向
          </>
        }
        options={industrys}
        fieldProps={{
          mode: 'multiple',
          allowClear: true,
        }}
      />
      <ProForm.Item
        label={
          <>
            <span
              style={{
                color: '#ff4d4f',
                fontSize: 14,
                paddingRight: 4,
              }}
            >
              *
            </span>
            标签
          </>
        }
        name="articleLabels"
        extra={
          <div
            style={{
              marginLeft: '28px',
            }}
          >
            最少输入一个
          </div>
        }
      >
        <TagGroup
          style={{
            marginLeft: '28px',
          }}
        />
      </ProForm.Item>
      <ProFormDatePicker
        name="articleSetDate"
        label={
          <span
            style={{
              marginLeft: 11,
            }}
          >
            线索日期
          </span>
        }
        width="xl"
        fieldProps={{
          allowClear: true,
          maxLength: 200,
          format: 'YYYY-MM-DD',
        }}
      />
      <ProFormTextArea
        name="articleLocation"
        label={
          <span
            style={{
              marginLeft: 11,
            }}
          >
            地点
          </span>
        }
        width="xl"
        fieldProps={{
          allowClear: true,
          rows: 3,
          maxLength: 100,
          showCount: true,
          style: {
            marginLeft: '28px',
          },
        }}
      />

      <ProFormTextArea
        name="articleHighlight"
        label={
          <span
            style={{
              marginLeft: 11,
            }}
          >
            亮点
          </span>
        }
        width="xl"
        fieldProps={{
          allowClear: true,
          rows: 3,
          maxLength: 100,
          showCount: true,
          style: {
            marginLeft: '28px',
          },
        }}
      />

      <ProFormList
        name="contacts"
        label="联络方式"
        creatorButtonProps={{
          creatorButtonText: '添加联络人',
        }}
        itemRender={({ listDom, action }, { index }) => {
          return (
            <ProCard
              bordered
              title={false}
              style={{
                marginBlockEnd: 8,
              }}
              bodyStyle={{
                paddingBottom: 0,
              }}
            >
              <Row>
                <Col span={23}>{listDom}</Col>
                <Col span={1}>{action}</Col>
              </Row>
            </ProCard>
          );
        }}
        copyIconProps={false}
      >
        <ProFormText
          width="md"
          name="name"
          label="联络人"
          required={true}
          fieldProps={{
            allowClear: true,
            maxLength: 200,
          }}
        />
        <ProFormText
          width="md"
          name="phone"
          label="联系电话"
          required={true}
          fieldProps={{
            allowClear: true,
            maxLength: 200,
          }}
          rules={[
            {
              pattern:
                /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/,
              message: '请输入正确的手机号',
            },
          ]}
        />
      </ProFormList>
      <ProCard ghost>
        <ProCard colSpan={green ? '750px' : '1'} ghost>
          <ProFormTextArea
            name="articleContent"
            label={
              <span>
                <span
                  style={{
                    color: '#ff4d4f',
                    fontSize: 14,
                    paddingRight: 4,
                  }}
                >
                  *
                </span>
                线索内容
              </span>
            }
            width="xl"
            fieldProps={{
              allowClear: true,
              rows: 5,
              maxLength: 200,
              showCount: true,
            }}
          />
        </ProCard>
        {green && (
          <ProCard ghost>
            <ProList
              extra={<a>aa</a>}
              rowKey="id"
              headerTitle={false}
              toolbar={{}}
              dataSource={[
                {
                  id: '1',
                  name: '语雀的天空',
                  image:
                    'https://gw.alipayobjects.com/zos/antfincdn/efFD%24IOql2/weixintupian_20170331104822.jpg',
                  desc: '我是一条测试的描述',
                },
                {
                  id: '2',
                  name: 'Ant Design',
                  image:
                    'https://gw.alipayobjects.com/zos/antfincdn/efFD%24IOql2/weixintupian_20170331104822.jpg',
                  desc: '我是一条测试的描述',
                },
                {
                  id: '3',
                  name: '蚂蚁金服体验科技',
                  image:
                    'https://gw.alipayobjects.com/zos/antfincdn/efFD%24IOql2/weixintupian_20170331104822.jpg',
                  desc: '我是一条测试的描述',
                },
                {
                  id: '4',
                  name: 'TechUI',
                  image:
                    'https://gw.alipayobjects.com/zos/antfincdn/efFD%24IOql2/weixintupian_20170331104822.jpg',
                  desc: '我是一条测试的描述',
                },
              ]}
              showActions="hover"
              editable={{
                onSave: async (key, record, originRow) => {
                  return true;
                },
              }}
              metas={{
                title: {
                  dataIndex: 'name',
                },
                description: {
                  dataIndex: 'desc',
                },

                actions: {
                  render: (text, row, index, action) => [
                    <a
                      onClick={() => {
                        action?.startEditable(row.id);
                      }}
                      key="link"
                    >
                      编辑
                    </a>,
                  ],
                },
              }}
            />
          </ProCard>
        )}
      </ProCard>
      <FormItem
        name="articleAttachments"
        hidden={!access.线索征集x报送线索x附件}
        label={
          <span
            style={{
              marginLeft: 11,
            }}
          >
            附件
          </span>
        }
      >
        <UploadDragger
          style={{
            marginLeft: '28px',
          }}
          onPreview={(file) => {}}
          access={{
            isPicture: access.线索征集x报送线索x附件x图片,
            isVideo: access.线索征集x报送线索x附件x视频,
            isOffice: access.线索征集x报送线索x附件x办公,
            isOther: access.线索征集x报送线索x附件x其他,
          }}
          url="/cues/attachment/save"
          mode="submit"
        />
      </FormItem>
    </DrawerForm>
  );
};
export default AddSubmit;
